package com.example.fushuang.balabala.activities;

import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.SystemClock;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.fushuang.balabala.R;
import com.example.fushuang.balabala.Util.MyTimeCompat;
import com.example.fushuang.balabala.adapter.CommenFragmentPagerAdapter;
import com.example.fushuang.balabala.client.ClientAPI;
import com.example.fushuang.balabala.fragment.AvPlayDiscussFragment;
import com.example.fushuang.balabala.fragment.AvPlayIntroduceFragment;
import com.example.fushuang.balabala.fragment.BaseFragment;
import com.example.fushuang.balabala.model.RecommendEntry;
import com.example.fushuang.balabala.model.VideoDetail;
import com.example.fushuang.balabala.model.VideoUrl;
import com.squareup.picasso.Picasso;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

public class AVActivity extends AppCompatActivity implements View.OnClickListener, SurfaceHolder.Callback, IMediaPlayer.OnPreparedListener, IMediaPlayer.OnBufferingUpdateListener, View.OnTouchListener {

    private RecommendEntry.ResultBean.BodyBean mBodyItem;
    private IjkMediaPlayer mPlayer;
    private VideoDetail mVideoDetail;
    private SurfaceView mSurfaceView;
    private TextView mCurrentTime;
    private TextView mTotal;
    private GestureDetectorCompat mDetectorCompat;
    private View mMediaController;
    private Handler mHandler=new Handler();
    private boolean first=false;
    private ViewPager mPager;
    private CommenFragmentPagerAdapter mPagerAdapter;
    private List<BaseFragment> mFragmentList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            first=true;
        }
        setContentView(R.layout.activity_video_play);
        EventBus.getDefault().register(this);
        mBodyItem = getIntent().getParcelableExtra("bodyItem");
        init();

    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        ClientAPI.getVideoDetail(mBodyItem.getParam());
        MobclickAgent.onResume(this);
        MobclickAgent.onPageStart("avPlay");
    }

    @Override
    protected void onPause() {
        MobclickAgent.onPageEnd("avPlay");
        MobclickAgent.onPause(this);
        super.onPause();
    }

    private void init() {
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.video_play_fab);
        if (fab != null) {
            fab.setOnClickListener(this);
        }
        Toolbar toolbar = (Toolbar) findViewById(R.id.video_play_toolbar);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }
        ImageView imageView = (ImageView) findViewById(R.id.video_play_cover);
        if (imageView != null) {
            Picasso.with(this).load(mBodyItem.getCover()).config(Bitmap.Config.RGB_565)
                    .resize(mBodyItem.getWidth(), mBodyItem.getHeight())
                    .into(imageView);
        }
        //获取控制器linearLayout
        mMediaController = findViewById(R.id.video_controller);

        ImageView fullScreenImg = (ImageView) findViewById(R.id.video_controller_fullScreen);
        fullScreenImg.setOnClickListener(this);
        mCurrentTime = (TextView) findViewById(R.id.video_controller_currentTime);
        mTotal = (TextView) findViewById(R.id.video_controller_totalTime);

        //子线程高级绘制工具,在子线程中绘制复杂的图像
        mSurfaceView = (SurfaceView) findViewById(R.id.video_play_surface);
        mSurfaceView.getHolder().addCallback(this);
        mSurfaceView.setOnTouchListener(this);



        //兼容包线面的手势识别器,实现点击拖拽的监听
        mDetectorCompat = new GestureDetectorCompat(this, new VideoGestureDetector());

        mPlayer = new IjkMediaPlayer();
        mPlayer.setOnPreparedListener(this);
        mPlayer.setOnBufferingUpdateListener(this);

        //设置评论区域的viewpager
        mPager = (ViewPager) findViewById(R.id.av_pager);
        if (mPager != null) {
            mFragmentList = new ArrayList<>();

            mFragmentList.add(new AvPlayIntroduceFragment());
            mFragmentList.add(new AvPlayDiscussFragment());
            mPagerAdapter = new CommenFragmentPagerAdapter(getSupportFragmentManager(), mFragmentList);
            mPager.setAdapter(mPagerAdapter);
            TabLayout tabLayout = (TabLayout) findViewById(R.id.av_tab_layout);
            tabLayout.setupWithViewPager(mPager);
        }


    }

    @Subscribe
    public void onReceiveDetail(VideoDetail detail) {
        mVideoDetail = detail;
        if (first){
            startVideoPlay();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)

    public void onReceivePlayUrl(VideoUrl videoUrl) {
        mSurfaceView.setVisibility(View.VISIBLE);
        List<VideoUrl.DurlBean> durl = videoUrl.getDurl();
        if (durl != null) {
            if (!durl.isEmpty()) {
                VideoUrl.DurlBean durlBean = durl.get(0);
                String url =  durlBean.getUrl();
                try {
                    // 设置视频、音频 的地址 需要网络 或者 IO流的读取
                    mPlayer.setDataSource(url);
                    // 异步子线程方式，开始准备视频，准备好就回调接口
                    mPlayer.prepareAsync();
                    //设置进度条中的歌曲信息
                    mTotal.setText(MyTimeCompat.converLongTimeToStr(durlBean.getLength()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.video_play_fab:
                startVideoPlay();
                break;
            case R.id.video_controller_fullScreen:
                int requestedOrientation = getRequestedOrientation();
                if (requestedOrientation== ActivityInfo.SCREEN_ORIENTATION_PORTRAIT||requestedOrientation==ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) {
                    // 垂直方向，那么切换成 水平方向
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }else if (requestedOrientation==ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
                break;
        }
    }

    private void startVideoPlay() {
        if (mVideoDetail != null) {
            List<VideoDetail.DataBean.PagesBean> pages = mVideoDetail.getData().getPages();
            if (pages != null && pages.size() > 0) {
                VideoDetail.DataBean.PagesBean page = pages.get(0);
                long cid = page.getCid();
                ClientAPI.getPlayUrlAsync(Long.toString(cid), 1, "mp4");
            }
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        //初始化 播放器或者照相机,设置投射谁的内容
        mPlayer.setDisplay(holder);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mPlayer.isPlaying()) {
            mPlayer.stop();
        }
        mPlayer.release();
    }

    // ----------------------
    // 当视频准备好的时候，方法回调
    @Override
    public void onPrepared(IMediaPlayer iMediaPlayer) {
        iMediaPlayer.start();
    }

    @Override
    public void onBufferingUpdate(IMediaPlayer iMediaPlayer, int i) {

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return mDetectorCompat.onTouchEvent(event);
    }

    private class VideoGestureDetector extends GestureDetector.SimpleOnGestureListener{

        private static final String SHOW_CONTROLLER = "show";
        /**
         * 按下事件，返回true才可以处理手势
         * @param e
         * @return
         */
        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        /**
         * 快速点击抬起的时候触发
         * @param e
         * @return
         */
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            mHandler.removeCallbacksAndMessages(SHOW_CONTROLLER);
            mMediaController.setVisibility(View.VISIBLE);
            long time = SystemClock.uptimeMillis() + 2000;
            mHandler.postAtTime(new Runnable() {
                @Override
                public void run() {
                    mMediaController.setVisibility(View.INVISIBLE);
                }
            },SHOW_CONTROLLER,time);

            return super.onSingleTapUp(e);
        }
    }
}
